//
//  WGQTransfersRecordsViewController.m
//  meiang_edu
//
//  Created by gq w on 2018/9/26.
//  Copyright © 2018年 com.meiang.meiang_edu. All rights reserved.
//  接送记录

#import "WGQTransfersRecordsViewController.h"
#import "WGQTransfersRecordsTableViewCell.h"//cell
#import "WGQTransfersRecordsHeaderView.h"//tableHeadeView
#import "WGQTransfersRecordsModel.h"//接送数据model
#import "WGQTransfersRecordsBabyModel.h"//当前宝宝的model
#import "WGQTransfersRecordsSectionHeaderView.h"//sectionHeaderView
#import "WGQTransfersRecordsAlertView.h"//黑色背景的弹框
#import "UIView+ShowView.h"//辅助

@interface WGQTransfersRecordsViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView * tableView;
@property (nonatomic,strong) NSMutableArray * tableArray;
@property (nonatomic,copy) NSString * currentYearStr;//年份的字符串
@property (nonatomic,copy) NSString * currentMonthStr;//月份的字符串

@property (nonatomic,copy) NSString * maxYearStr;//最大y年份
@property (nonatomic,copy) NSString * maxMonthStr;//z最大月份

@property (nonatomic,strong) NSMutableArray * babyArray;//宝宝数组
@property (nonatomic,strong) WGQTransfersRecordsBabyModel * currentBabyModel;//当前的宝宝的model
@property (nonatomic,strong) WGQTransfersRecordsHeaderView * headerView;
@property (nonatomic,strong) WGQTransfersRecordsSectionHeaderView * sectionHeaderView;

@end

@implementation WGQTransfersRecordsViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"接送记录";
    self.view.backgroundColor = FFColor(0xEBEBEB);
    self.tableArray = [NSMutableArray array];
    self.babyArray = [NSMutableArray array];
    [self takeMaxTime];
    [self takeCurrentTime];
    [self addSubViews];
    [self requestBabyData];
}

- (void)takeCurrentTime
{
    //获取当前年月
    NSDate * senddate = [NSDate date];
    
    NSDateFormatter * dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy"];
    self.currentYearStr = [dateformatter stringFromDate:senddate];
    
    NSDateFormatter * dateformatter1 = [[NSDateFormatter alloc] init];
    [dateformatter1 setDateFormat:@"MM"];
    self.currentMonthStr = [dateformatter1 stringFromDate:senddate];
}

- (void)takeMaxTime
{
    //最晚到当前月份的后两个月
    NSDate * senddate = [NSDate date];
    
    NSDateFormatter * dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy"];
    self.maxYearStr = [dateformatter stringFromDate:senddate];
    
    NSDateFormatter * dateformatter1 = [[NSDateFormatter alloc] init];
    [dateformatter1 setDateFormat:@"MM"];
    self.maxMonthStr = [dateformatter1 stringFromDate:senddate];
    //当前月份为11或者12月份的时候，就需要跨年
    if ([self.maxMonthStr isEqualToString:@"11"])
    {
        self.maxYearStr = [NSString stringWithFormat:@"%ld",[self.maxYearStr integerValue] + 1];
        self.maxMonthStr = @"01";
    }
    else if ([self.maxMonthStr isEqualToString:@"12"])
    {
        self.maxYearStr = [NSString stringWithFormat:@"%ld",[self.maxYearStr integerValue] + 1];
        self.maxMonthStr = @"02";
    }
    else
    {
        self.maxMonthStr = [NSString stringWithFormat:@"%ld",[self.maxMonthStr integerValue] + 2];
    }
}

//获取宝宝数据
- (void)requestBabyData
{
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request)
     {
         request.requestSerializerType = ZBJSONRequestSerializer;
         request.URLString = [NSString stringWithFormat:@"%@%@?entity_type=user_child&status=1",Pick_up_baby,userinfo.ID];
         request.methodType = ZBMethodTypeGET;
         [request setValue:userinfo.token forHeaderField:@"token"];
         request.apiType = ZBRequestTypeRefresh;
     } success:^(id responseObject, apiType type)
     {
         [MBManager hideAlert];
         // 解析数据
         NSDictionary * dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
         DLog(@"%@",dataDict);
         NSInteger code = [dataDict[@"msgcode"] integerValue];
         if (code == 1)
         {
             // 请求成功
             [MBManager hideAlert];
             //处理当前账户的babay数据源
             NSArray * array = dataDict[@"value"];
             [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop)
             {
                 WGQTransfersRecordsBabyModel * model = [[WGQTransfersRecordsBabyModel alloc]initWithDictionary:obj];
                 [self.babyArray addObject:model];
             }];
             if (self.babyArray.count > 0)
             {
                 self.currentBabyModel = self.babyArray[0];
             }
             //刷新宝宝信息
             [self.headerView changeBabyMessageWithModel:self.currentBabyModel];
             //刷新年月信息
             [self.headerView changeTimeLabelTextWithYearStr:self.currentYearStr monthStr:self.currentMonthStr];
             //请求当前宝宝的接送记录
             [self requestDataWithYear:self.currentYearStr month:self.currentMonthStr];
         }
         else
         {
             [MBManager showBriefAlert:dataDict[@"message"]];
         }
     } failure:^(NSError *error)
     {
         DLog(@"%@",error);
         
     } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache)
     {
         if (isCache==YES)
         {
             DLog(@"使用了缓存");
         }
     }];
}


//根据宝宝获取接送记录
- (void)requestDataWithYear:(NSString *)yearStr month:(NSString *)monthStr
{
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request)
     {
         request.requestSerializerType = ZBJSONRequestSerializer;
         request.URLString = [NSString stringWithFormat:@"%@%@?iyear=%@&imonth=%@",Baby_pick_up,self.currentBabyModel._id,self.currentYearStr,self.currentMonthStr];
         request.methodType = ZBMethodTypeGET;
         [request setValue:userinfo.token forHeaderField:@"token"];
         request.apiType = ZBRequestTypeRefresh;
     } success:^(id responseObject, apiType type)
     {
         [MBManager hideAlert];
         // 解析数据
         NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
         DLog(@"%@",dataDict);
         NSInteger code = [dataDict[@"msgcode"] integerValue];
         if (code == 1)
         {
             // 请求成功
             [MBManager hideAlert];
             NSArray * array = dataDict[@"value"];
             if (self.tableArray.count > 0)
             {
                 [self.tableArray removeAllObjects];
             }
             [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop)
              {
                  WGQTransfersRecordsModel * model = [[WGQTransfersRecordsModel alloc] initWithDictionary:obj];
                  [self.tableArray addObject:model];
              }];
             [self.tableView reloadData];
         }
         else
         {
             [MBManager showBriefAlert:dataDict[@"message"]];
         }
     } failure:^(NSError *error)
     {
         DLog(@"%@",error);
         
     } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache)
     {
         if (isCache==YES)
         {
             DLog(@"使用了缓存");
         }
     }];
}

- (void)addSubViews
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    if (@available(iOS 11.0, *))
    {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    self.tableView.backgroundColor = FFColor(0xEBEBEB);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 180 * kScale;
    [self.tableView registerClass:[WGQTransfersRecordsTableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.equalTo(self.view.mas_left).offset(4 * kScale);
         make.right.equalTo(self.view.mas_right).offset(-4 * kScale);
         make.bottom.equalTo(self.view.mas_bottom);
         make.top.equalTo(self.view.mas_top).offset([UIApplication sharedApplication].statusBarFrame.size.height + self.navigationController.navigationBar.frame.size.height);
     }];
    
    __weak __typeof(&*self)weakSelf = self;
    self.headerView = [[WGQTransfersRecordsHeaderView alloc] initWithFrame:CGRectMake(0, 0, 0, 116 * kScale)];
    self.tableView.tableHeaderView = self.headerView;
    self.headerView.is_left_click_block = ^(BOOL isLeft)
    {
        [weakSelf changeYearAndMonthWithisLeft:isLeft];
    };
    
    self.headerView.is_click = ^(BOOL isClick)
    {
        if (isClick == YES)
        {
            [weakSelf creatAlrtView];
        }
    };
}

//改变当前数据的
- (void)changeYearAndMonthWithisLeft:(BOOL)isLeft
{
    if (isLeft == YES)
    {
        //最早到2018.9
        if ([self.currentYearStr isEqualToString:@"2018"] && [self.currentMonthStr isEqualToString:@"09"])
        {
            return;
        }
        //往前翻一个月
        NSInteger month = [self.currentMonthStr integerValue];
        if (month == 1)
        {
            //翻年
            self.currentYearStr = [NSString stringWithFormat:@"%.2ld",(long)[self.currentYearStr integerValue] - 1];
            self.currentMonthStr = @"12";
        }
        else
        {
            self.currentMonthStr = [NSString stringWithFormat:@"%.2ld",(long)month - 1];
        }
    }
    else
    {
        //已达到最后的时间限制
        if ([self.currentYearStr isEqualToString:self.maxYearStr] && [self.currentMonthStr isEqualToString:self.maxMonthStr])
        {
            return;
        }
        //往后翻一个月
        NSInteger month = [self.currentMonthStr integerValue];
        if (month == 12)
        {
            //翻年
            self.currentYearStr = [NSString stringWithFormat:@"%.2ld",(long)[self.currentYearStr integerValue] + 1];
            self.currentMonthStr = @"01";
        }
        else
        {
            self.currentMonthStr = [NSString stringWithFormat:@"%.2ld",(long)month + 1];
        }
    }
    //刷新时间label的显示
    [self.headerView changeTimeLabelTextWithYearStr:self.currentYearStr monthStr:self.currentMonthStr];
    //根据当前时间请求数据
    [self requestDataWithYear:self.currentYearStr month:self.currentMonthStr];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tableArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WGQTransfersRecordsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    [cell setObject:self.tableArray[indexPath.row]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 36 * kScale;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (!self.sectionHeaderView)
    {
        self.sectionHeaderView = [[WGQTransfersRecordsSectionHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth - 8 * kScale, 36 * kScale)];
    }
    [self.sectionHeaderView changeTimeLabelTextWithYearStr:self.currentYearStr monthStr:self.currentMonthStr];
    return self.sectionHeaderView;
}

- (void)creatAlrtView
{
    WGQTransfersRecordsAlertView * alertView = [[WGQTransfersRecordsAlertView alloc] initWithFrame:CGRectMake(100 * kScale, (kScreenHeight - self.babyArray.count * 40 * kScale)/2, 160 * kScale, self.babyArray.count * 40 * kScale) andTitleArray:self.babyArray];
    alertView.layer.masksToBounds = YES;
    alertView.layer.cornerRadius = 4 * kScale;
    [alertView show];
    
    //弹框数据的回调
    __weak __typeof(&*self)weakSelf = self;
    alertView.click_index_block = ^(NSInteger index)
    {
        //可以是字符串，也可以是WGQHomeAlertViewModel
        weakSelf.currentBabyModel = weakSelf.babyArray[index];
        [weakSelf takeCurrentTime];
        [weakSelf.headerView changeBabyMessageWithModel:self.currentBabyModel];
        [weakSelf.headerView changeTimeLabelTextWithYearStr:self.currentYearStr monthStr:self.currentMonthStr];
        [weakSelf requestDataWithYear:self.currentYearStr month:self.currentMonthStr];
    };
}

@end
